package com.contain.gateway.security;

import cn.hutool.core.util.StrUtil;
import com.contain.common.constant.AuthConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: tianchao
 * @Date: 2021/7/8 23:25
 * @Description:
 */
@Component
@Slf4j
public class SecurityGlobalFilter implements GlobalFilter, Ordered {

    private RedisTemplate redisTemplate;

    public SecurityGlobalFilter(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 非JWT或者JWT为空不作处理
       ;
        String token = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION_KEY);
        if (StrUtil.isBlank(token) || !token.startsWith(AuthConstants.AUTHORIZATION_PREFIX)) {
            log.info("SecurityGlobalFilter 过滤器开始");
            Mono<Void> filter = chain.filter(exchange);
            log.info("SecurityGlobalFilter 过滤器结束");
            return filter;
        }

        log.error("[进入这里了吗]");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
